package com.thunbu.thunbu_meeting_system.activity

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.cathu.lib_commonkt.base.BaseMVVMActivity
import com.google.gson.Gson
import com.hjq.toast.ToastUtils
import com.honeywell.aidc.*
import com.honeywell.rfidservice.rfid.OnTagReadListener
import com.honeywell.rfidservice.rfid.TagAdditionData
import com.honeywell.rfidservice.rfid.TagReadData
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.thunbu.lib_common.function.Action
import com.thunbu.lib_common.utils.JsonUtils
import com.thunbu.lib_common.widget.CommonToolBar
import com.thunbu.thunbu_meeting_system.*
import com.thunbu.thunbu_meeting_system.bean.AssetModel
import com.thunbu.thunbu_meeting_system.bean.StockModel
import com.thunbu.thunbu_meeting_system.databinding.*
import com.thunbu.thunbu_meeting_system.dialog.OperatConfirmPop
import com.thunbu.thunbu_meeting_system.dialog.OperatPop
import com.thunbu.thunbu_meeting_system.dialog.ScanPop
import com.thunbu.thunbu_meeting_system.dialog.SearchPop
import com.thunbu.thunbu_meeting_system.listener.EventSimpleListener
import com.thunbu.thunbu_meeting_system.rfid.WorkMode
import com.thunbu.thunbu_meeting_system.utils.SpUtils
import com.thunbu.thunbu_meeting_system.viewMdel.InventoryTaskListViewModel
import kotlinx.android.synthetic.main.activity_inventory.view.*
import kotlinx.android.synthetic.main.include_inventory.view.*
import kotlinx.android.synthetic.main.include_search_bar.*
import java.lang.NullPointerException
import java.util.*
import kotlin.concurrent.thread

/**
 * 资产盘点
 */
class InventoryActivity : BaseMVVMActivity<ActivityInventoryBinding,
        InventoryTaskListViewModel>(),BarcodeReader.TriggerListener,BarcodeReader.BarcodeListener,EventSimpleListener{
    companion object{
        const val STOCKTASK_CODE = "stockTaskCode"
        const val IS_EDIT = "IS_EDIT"
    }
    lateinit var  manager: AidcManager
    var barcodeReader: BarcodeReader?=null

    var mTagDataList= mutableListOf<TagReadData>()

    lateinit var toolBar: CommonToolBar

    private lateinit var mAdapter1: BaseVBQuickAdapter<AssetModel, InventoryListItemBinding>
    private lateinit var mAdapter2: BaseVBQuickAdapter<AssetModel, InventoryListItem3Binding>

    private lateinit var headView: View

    private var mTargetSwitchInterval = 3000
    private var mCurrentTarget = 0 // 0 A, 1 B


    @Volatile
    private var mNormalReadThreadRun = false

    @Volatile
    private var scanIng = false

    lateinit var stockModel:StockModel
    val ORIGINAL_PAGE = 1
    var mPage = ORIGINAL_PAGE
    var mAssetStatus = 0 //当前资产盘点状态 0 待盘点; 1 盘存; 2 盘亏,3为盘盈
    var checkCount = 0
    var isEdit = true //是否可编辑状态
    var isCheckAll = false //是否全选状态
    var searchPop : SearchPop?=null


    override fun onMVVMCreated() {
        stockModel= JsonUtils.fromJson(intent.extras?.getString(STOCKTASK_CODE),StockModel::class.java)
        isEdit = intent.extras?.getBoolean(IS_EDIT,true)?:true
        headView=bindViews.linlayoutHead
        initToolBar()
        initListener()
        initView()
        initRv()
        bindAdapter1()
        initScan()
        initVM()
        loadData(true)

    }

    private fun initVM() {

        vm.gs1Model.observe(this){
            Log.e("fancl","回调结果")
            showScanPop(it)
        }

        vm.stockInfoPage.observe(this){
            if(!it.list.isNullOrEmpty()){
                stockModel = it.list[0]
                initHeadWithData()
            }
        }
        vm.operateResult.observe(this){
            reset()
            loadData(true)
        }
        vm.assetPage.observe(this){
            bindViews.refereshLayout.finishLoadMore()
            var mAdapter = if(mAssetStatus == 0){
                mAdapter1
            }else{
                mAdapter2
            }
            var needBatch = bindViews.ll2.visibility == View.VISIBLE
            it?.list?.forEach { model->
                model.isBatch = needBatch
                model.isChecked = isCheckAll
            }
            if (mPage == ORIGINAL_PAGE) {
                mAdapter.setNewData(it?.list)
            } else {
                mAdapter.addData(it?.list?: mutableListOf())
            }
            if(it?.total?:0 > mAdapter.itemCount+1){
                mPage++
            }else{
                bindViews.refereshLayout.setEnableLoadMore(false)
            }
        }
    }

    private fun loadData(needRefreshHead:Boolean = false) {
        if(needRefreshHead) vm.requestStockInfo(stockModel.stockTaskCode)
        vm.queryAssetList(stockModel.stockTaskCode,
                mAssetStatus,
                zcType,
                zcName,
                brand,
                model,
                user,
                department,
                address,
                mPage,
                20
        )
    }



    val changeOperate= {status:Int->

        val ids = if(mAssetStatus == 0){
            mAdapter1.data.filter { it.isChecked }.map { it.id }
        }else{
            mAdapter2.data.filter { it.isChecked }.map { it.id }
        }
        //盘盈撤回等于删除
        if(mAssetStatus == 3){
            vm.deleteSurplus(ids)
        }else{
            operate(status,ids)
        }
    }

    private fun operate(operateType:Int,ids:List<String?>,callback:Action? = null){
        val operatConfirmPop = OperatConfirmPop(this) {
            callback?.run()
            vm.operate(mAssetStatus,operateType, ids,stockModel.stockTaskCode,it)
        }
        XPopup.Builder(this).popupAnimation(PopupAnimation.NoAnimation)
                .dismissOnTouchOutside(false)
                .asCustom(operatConfirmPop)
                .show()
    }

    private fun initScan(){
        AidcManager.create(this) { aidcManager ->
            manager = aidcManager //获得Aidc管理器对象
            barcodeReader = manager.createBarcodeReader() //创建BarcodeReader对象
            //第二步：设置扫描属性

            //第二步：设置扫描属性
            try {
                barcodeReader?.setProperty(BarcodeReader.PROPERTY_CODE_128_ENABLED, true)
                barcodeReader?.setProperty(BarcodeReader.PROPERTY_QR_CODE_ENABLED, true)
                barcodeReader?.setProperty(BarcodeReader.PROPERTY_DATA_PROCESSOR_LAUNCH_BROWSER,false)
                barcodeReader?.setProperty(
                    BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE,
                    BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL
                )
                barcodeReader?.claim() //打开扫描功能
            } catch (e: Exception) {
                Log.i("fancl","初始化扫码枪失败:"+e.localizedMessage)
            }
            //第三步：注册Trigger监听器和Barcode监听器

            //第三步：注册Trigger监听器和Barcode监听器
            barcodeReader?.addTriggerListener(this@InventoryActivity)
            barcodeReader?.addBarcodeListener(this@InventoryActivity)
        }
    }

    private fun initListener(){
        bindViews.tvXzpy.setOnClickListener {
            val intent = Intent(this@InventoryActivity,InventoryAddActivity::class.java)
            intent.putExtra(STOCKTASK_CODE, Gson().toJson(stockModel))
            startActivityForResult(intent,1)
        }

        headView.lin1.setOnClickListener {
            if(mAssetStatus == 0) return@setOnClickListener
            mAssetStatus = 0
            restUi()
            headView.tv_layout1_dpd.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_dpd.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view1.visibility=View.VISIBLE
//            bindViews.linAction.visibility = View.VISIBLE
            reset()
            bindAdapter1()
            loadData()
        }
        headView.lin2.setOnClickListener {
            if(mAssetStatus == 1) return@setOnClickListener
            mAssetStatus = 1
            restUi()
            headView.tv_layout2_pcs.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_pcs.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view2.visibility=View.VISIBLE
//            bindViews.linAction.visibility = View.GONE
            reset()
            bindAdapter2()
            loadData()
        }
        headView.lin3.setOnClickListener {
            if(mAssetStatus == 3) return@setOnClickListener
            mAssetStatus = 3
            restUi()
            headView.tv_layout3_pys.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_pys.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view3.visibility=View.VISIBLE
//            bindViews.linAction.visibility = View.GONE
            reset()
            bindAdapter2()
            loadData()
        }
        headView.lin4.setOnClickListener {
            if(mAssetStatus == 2) return@setOnClickListener
            mAssetStatus = 2
            restUi()
            headView.tv_layout4_pks.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.tv_pks.setTextColor(resources.getColor(R.color.color_3375f6))
            headView.view4.visibility=View.VISIBLE
//            bindViews.linAction.visibility = View.GONE
            reset()
            bindAdapter2()
            loadData()
        }
    }

    private fun reset(){
        mPage = ORIGINAL_PAGE
        bindViews.refereshLayout.setEnableLoadMore(true)
        bindViews.ll1.visibility = isEdit.ternary(View.VISIBLE,View.GONE)
        bindViews.ll2.visibility = View.GONE
        checkCount = 0
        bindViews.tvCheckSize.text = ""
        isCheckAll = false
        bindViews.tvCheckall.text = if(isCheckAll) "取消" else "全选"
        zcType = null
        zcName = null
        brand = null
        model = null
        user = null
        department = null
        address = null
        searchPop?.clean()
    }

    private fun restUi(){
        headView.view1.visibility=View.INVISIBLE
        headView.view2.visibility=View.INVISIBLE
        headView.view3.visibility=View.INVISIBLE
        headView.view4.visibility=View.INVISIBLE
        headView.tv_layout1_dpd.setTextColor(resources.getColor(R.color.color_333333))
        headView.tv_dpd.setTextColor(resources.getColor(R.color.color_999999))
        headView.tv_layout2_pcs.setTextColor(resources.getColor(R.color.color_333333))
        headView.tv_pcs.setTextColor(resources.getColor(R.color.color_999999))
        headView.tv_layout3_pys.setTextColor(resources.getColor(R.color.color_F54545))
        headView.tv_pys.setTextColor(resources.getColor(R.color.color_999999))
        headView.tv_layout4_pks.setTextColor(resources.getColor(R.color.color_3FCB7A))
        headView.tv_pks.setTextColor(resources.getColor(R.color.color_999999))
    }

    private fun initHeadWithData(){

        headView.tv_title.text=stockModel.stockTaskName
        headView.tv_title_count.text=stockModel.count?.toString()
        headView.tv_title_status.text= when(stockModel.stockStatus){
            0 ->  "未盘点"
            1 ->  "盘点中"
            2 ->  "已完成盘点"
            3 ->  "已终止盘点"
            else-> ""
        }
        headView.tv_title_date.text=stockModel.createTime
        headView.tv_layout1_dpd.text=stockModel.toBeCounted?.toString()
        headView.tv_layout2_pcs.text=stockModel.inventoryCount?.toString()
        headView.tv_layout3_pys.text=stockModel.diskSurplusCount?.toString()
        headView.tv_layout4_pks.text=stockModel.orderLossCount?.toString()
    }

    private fun initRv(){
        bindViews.rlList.layoutManager = LinearLayoutManager(this)
    }


    private fun bindAdapter2(){
        mAdapter2 = bindViews.rlList.bindAdapter { item, position ->
            itemInclude.tvName.text = item.zichanmc
            itemInclude.tvNumber.text = item.zichanbh
            itemInclude.tvType.text = item.zichanflmc
            itemInclude.tvAdr.text = item.cunfangddid
            ivSelect.visibility = item.isBatch.ternary(View.VISIBLE,View.GONE)
            ivSelect.setImageResource(item.isChecked.ternary(R.mipmap.select,R.mipmap.un_select))
            ivSelect.setOnClickListener {
                item.isChecked = !item.isChecked
                mAdapter2.notifyItemChanged(position)
                if(item.isChecked){
                    checkCount++
                }else{
                    checkCount--
                }
                bindViews.tvCheckSize.text = checkCount.toString()
            }
            deleteLayout.setOnClickListener {
                //盘盈撤回等于删除
                if(mAssetStatus == 3){
                    vm.deleteSurplus(mutableListOf(item.id))
                }else{
                    operate(0, mutableListOf(item.id)){
                        swipeRl.close(false)
                    }
                }
            }
            itemInclude.root.setOnClickListener {
                val intent = Intent(this@InventoryActivity,InventoryDetailActivity::class.java)
                intent.putExtra(InventoryDetailActivity.ID,item.id)
                startActivityForResult(intent,2)
            }
            if(!isEdit){
                swipeRl.setLockDrag(true)
            }
        }
    }

    private fun bindAdapter1() {
        mAdapter1 = bindViews.rlList.bindAdapter { item, position ->
            tvName.text=item.zichanmc
            tvNumber.text=item.zichanbh
            tvType.text=item.zichanflmc
            tvAdr.text=item.cunfangddid
            ivSelect.visibility = item.isBatch.ternary(View.VISIBLE,View.GONE)
            line4.visibility = item.isBatch.ternary(View.VISIBLE,View.GONE)
            tvPc.visibility = item.isBatch.ternary(View.GONE,View.VISIBLE)
            tvPk.visibility = item.isBatch.ternary(View.GONE,View.VISIBLE)
            line2.visibility = item.isBatch.ternary(View.GONE,View.VISIBLE)
            line3.visibility = item.isBatch.ternary(View.GONE,View.VISIBLE)
            if(!isEdit){
                line4.visibility = View.VISIBLE
                tvPc.visibility = View.GONE
                tvPk.visibility = View.GONE
                line2.visibility= View.GONE
                line3.visibility= View.GONE
            }
            ivSelect.setImageResource(item.isChecked.ternary(R.mipmap.select,R.mipmap.un_select))
            ivSelect.setOnClickListener {
                item.isChecked = !item.isChecked
                mAdapter1.notifyItemChanged(position)
                if(item.isChecked){
                    checkCount++
                }else{
                    checkCount--
                }
                bindViews.tvCheckSize.text = checkCount.toString()
            }
            tvPk.setOnClickListener{
                operate(1, mutableListOf(item.id))
            }
            tvPc.setOnClickListener {
                operate(2, mutableListOf(item.id!!))
            }
        }
        mAdapter1.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this@InventoryActivity,InventoryDetailActivity::class.java)
            intent.putExtra(InventoryDetailActivity.ID,mAdapter1.data[position].id)
            intent.putExtra(InventoryDetailActivity.IS_EDIT,isEdit)
            startActivityForResult(intent,2)
        }
    }

    private fun initView(){
        //详情状态下隐藏顶部和底部操作按钮
        if(!isEdit){
            bindViews.ll1.visibility = View.GONE
            bindViews.ll2.visibility = View.GONE
        }
        bindViews.refereshLayout.setEnableRefresh(false)
        bindViews.refereshLayout.setEnableLoadMoreWhenContentNotFull(false)
        bindViews.refereshLayout.setEnableLoadMore(true)
        bindViews.refereshLayout.setOnLoadMoreListener {
            loadData()
        }
        bindViews.linAction.setOnClickListener {
            if(mAssetStatus == 0&&!mAdapter1.data.isNullOrEmpty()){
                showBatchUI(true,mAdapter1)
            } else if(mAssetStatus != 0&&!mAdapter2.data.isNullOrEmpty()){
                showBatchUI(true,mAdapter2)
            }
        }
        et_search.isFocusable = false
        et_search.isFocusableInTouchMode = false
        et_search.setOnClickListener {
            showSearchPop()
        }
        search_bar.setOnClickListener {
            showSearchPop()
        }
        bindViews.tvConfirm.setOnClickListener {
            showOperatePop()
        }
        bindViews.tvCheckall.setOnClickListener {
            isCheckAll = !isCheckAll
            val mAdapter = if(mAssetStatus == 0) mAdapter1 else mAdapter2
            mAdapter.data.forEach {
                it.isChecked  = isCheckAll
            }
            mAdapter.notifyDataSetChanged()
            checkCount = if(isCheckAll) mAdapter.data.size else 0
            bindViews.tvCheckSize.text = checkCount.toString()
            bindViews.tvCheckall.text = if(isCheckAll) "取消" else "全选"
        }

        searchPop = SearchPop(this) {isreset,type, zc, brand, model, user, department, address ->
            reset()
            zcType = type
            zcName = zc
            this.brand = brand
            this.model = model
            this.user = user
            this.department = department
            this.address = address
            loadData(false)
        }
    }

    var zcType:String? = null
    var zcName: String? = null
    var brand: String? = null
    var model: String? = null
    var user: String? = null
    var department: String? = null
    var address: String? = null
    private fun showSearchPop() {
        XPopup.Builder(this)
                .asCustom(searchPop)
                .show()
    }

    private fun showBatchUI(needBatch: Boolean,adapter:BaseVBQuickAdapter<AssetModel, *>) {
        adapter.data.forEach {
            it.isBatch  = needBatch
        }
        adapter.notifyDataSetChanged()
        bindViews.ll1.visibility = needBatch.ternary(View.GONE,View.VISIBLE)
        bindViews.ll2.visibility = needBatch.ternary(View.VISIBLE,View.GONE)
    }


    private fun initToolBar() {
        toolBar = setToolBar(CommonToolBar::class.java)
        toolBar.setBackAction {
            finish()
//            vm.frid(mutableListOf(
//                    "FFFFFFFF466D577437327148",
//                    "FFFFFFFF376A524C386F7A39",
//                    "FFFFFFFF776F496233644538",
//                    ),stockModel.stockTaskCode)
        }
        toolBar.setTitle(getString(R.string.title3))
        if(isEdit){
            toolBar.setSubTitleRight("开始扫描") {
                if (scanIng) {  //已经在开始扫描了
                    scanIng = false
                    (this as TextView).text = "开始扫描"
                    stopRead()
                    if (mTagDataList.isNotEmpty()) {
                        var result = ""
                        mTagDataList.forEach {
                            result = result.plus(it.epcHexStr).plus(",")
                        }
                        Log.i("InventoryActivity","扫描之后的结果:$result")
//                    ToastUtils.show("扫描之后的结果:$result")
                        vm.frid(mTagDataList.map { it.epcHexStr }.distinct(),stockModel.stockTaskCode)
                    }else{
                        ToastUtils.show("已扫描0条")
                    }
                } else {
                    (this as TextView).text = "停止扫描"
                    scanIng = true
                    read()
                }
            }
        }
    }


    private fun lightButton(){
        bindViews.linSaoma.setBackgroundResource(R.drawable.shape_bg_3375f6_no_stock_6)
        bindViews.linSaoma.tv_sm.setTextColor(resources.getColor(R.color.white))

    }

    private fun darkButton(){
        bindViews.linSaoma.setBackgroundResource(R.drawable.shape_bg_3375f6_6)
        bindViews.linSaoma.tv_sm.setTextColor(resources.getColor(R.color.color_3375f6))
    }

    //
    override fun onTriggerEvent(triggerStateChangeEvent: TriggerStateChangeEvent) {
        try {
            barcodeReader?.light(triggerStateChangeEvent.getState()) //开关补光
            barcodeReader?.aim(triggerStateChangeEvent.getState()) //开关瞄准线
            barcodeReader?.decode(triggerStateChangeEvent.getState()) //开关解码功能


            if(triggerStateChangeEvent.state){
                if(scanPop != null ){
                    if(scanPop?.isShown==true){
                       runOnUiThread {
                           scanPop?.dismiss()
                           scanPop=null
                       }
                    }
                }
                lightButton()
            }else{
                darkButton()
            }
        } catch (e: Exception) {
            println(e)
        }
    }

    //第四步：实现触发键事件和条码事件的处理
    override fun onBarcodeEvent(barcodeReadEvent: BarcodeReadEvent) {
        val result =barcodeReadEvent.getBarcodeData()		//获取扫描数据
        runOnUiThread {
//            if(System.currentTimeMillis()>1693532965000){
//                throw NullPointerException()
//            }
//            ToastUtils.show("扫码结果:"+result)
            if(result.contains("gs1=")){
                vm.requestGs1Info(result.split("gs1=")[1],stockModel.stockTaskCode)
            }else if(result.contains("guid="))
                vm.requestGuidInfo(result.split("guid=")[1],stockModel.stockTaskCode)
            else{
                ToastUtils.show("识别失败")
            }


        }

    }

    override fun onFailureEvent(p0: BarcodeFailureEvent?) {

    }


    override fun onResume() {
        super.onResume()
        if (barcodeReader != null) {
            try {
                barcodeReader?.claim()
            } catch (e: Exception) {

            }
        }
        App.instance.rfidMgr?.addEventListener(this)

    }

    override fun onPause() {
        super.onPause()
        if (barcodeReader != null) {
            barcodeReader?.release()
        }
        App.instance.rfidMgr?.removeEventListener(this)

        scanIng = false
        findViewById<TextView>(com.thunbu.lib_common.R.id.toolbar_SubtitleRight).text="开始扫描"
        stopRead()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (barcodeReader != null) {
            Log.i("fancl","onDestroy")
            barcodeReader?.removeTriggerListener(this)
            barcodeReader?.removeBarcodeListener(this)
            barcodeReader?.close()
        }
        if (this::manager.isInitialized) {
            manager.close()
        }
    }


    override fun onRfidTriggered(trigger: Boolean) {
        super.onRfidTriggered(trigger)
        if (!scanIng || !trigger) {
            stopRead()
        } else {
            read()
        }
    }

    var readThread:Thread?=null
    fun read(){
        if (!App.instance.isReaderAvailable()) {
            return
        }
        synchronized(mTagDataList) { mTagDataList.clear() }

        val mode = WorkMode.getInstance(App.instance.mRfidReader?.isHonReader()?:false).currentScenarioId
        // Normal mode
        mNormalReadThreadRun = true
        readThread=thread {
            val additionDataType: String = SpUtils.getString(
                getString(R.string.settings_key_addition_data), "None"
            )
            val tagAddition = TagAdditionData.get(additionDataType)
            var lastReadTime = System.currentTimeMillis()
            while (mNormalReadThreadRun) {
                val tags = App.instance.mRfidReader?.syncRead(tagAddition, 200)


                tags?.let {
                    tagListener.onTagRead(it)
                    val currentTime = System.currentTimeMillis()
                    if (mode == WorkMode.Modes.MODE_MASS_TAG_MULTI_INVENTORY.value()) {
                        if(tags.size ==0){
                            if (currentTime - lastReadTime > mTargetSwitchInterval) {
                                if (currentTime - lastReadTime > mTargetSwitchInterval) {
                                    switchTarget()
                                    lastReadTime = currentTime
                                }
                            }
                        }else{
                            lastReadTime = currentTime
                        }
                    }else{
                        lastReadTime = currentTime
                    }
                }

            }

        }
    }

    private val tagListener = OnTagReadListener{ it->
        synchronized(mTagDataList){
            it?.let { itInner->
                itInner.forEach { trd->
                   val epc = trd.getEpcHexStr()
                   val result =  mTagDataList.find { data->
                        data.epcHexStr.equals(epc)
                    }
                    if(result ==null){
                        mTagDataList.add(trd)
                    }

                }
            }
        }
    }

    private fun switchTarget() {

        App.instance.mRfidReader?.apply {
            mCurrentTarget = if (0 == mCurrentTarget) {
                this.setTarget(1)
                1
            } else {
                this.setTarget(0)
                0
            }
        }

    }

    private fun stopRead(){
        if (!App.instance.isReaderAvailable()) {
            return
        }

        // Normal mode
        mNormalReadThreadRun = false
        readThread?.apply {
            interrupt()
            readThread = null
        }
    }



    var scanPop:ScanPop?=null
    private fun showScanPop(assetModel: AssetModel) {
        Handler().postDelayed({
            scanPop = ScanPop(this,assetModel)
            XPopup.Builder(this).popupAnimation(PopupAnimation.NoAnimation)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .asCustom(scanPop).show()
        },300)


    }

    private fun showOperatePop() {
        if(checkCount == 0){
            ToastUtils.show("请选择资产")
            return
        }
        XPopup.Builder(this).popupAnimation(PopupAnimation.NoAnimation)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(OperatPop(this,changeOperate,mAssetStatus == 0)).show()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK){
            reset()
            loadData(true)
        }
    }

    override fun onBackPressed() {
        var needBatch = bindViews.ll2.visibility == View.VISIBLE
        if(needBatch){
            bindViews.ll1.visibility = isEdit.ternary(View.VISIBLE,View.GONE)
            bindViews.ll2.visibility = View.GONE
            checkCount = 0
            bindViews.tvCheckSize.text = ""
            isCheckAll = false
            bindViews.tvCheckall.text = if(isCheckAll) "取消" else "全选"
            var mAdapter = if(mAssetStatus == 0){
                mAdapter1
            }else{
                mAdapter2
            }
            mAdapter.data.forEach {
                it.isBatch = false
                it.isChecked = false
            }
            mAdapter.notifyDataSetChanged()
        }else{
            super.onBackPressed()
        }
    }

}